# 两种错误很容易辨认：语法错误和异常

import sys
import ostest

# 语法错误或者称之为解析错
# while True: print('Hello world')
#   File "<stdin>", line 1, in ?
#     while True print('Hello world')

try:
    # os.mknod("/myfile.txt")
#    f = open("/myfile.txt")
#    s = f.readline()
    s = "3"
#    i = int(s.strip())
except OSError as err:
    print("OS Error {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print("Can not open:", arg)
    else:
        print(arg, "has", f.readline(), "lines")
        f.close()

def this_fails():
    x = 1/0

try:
    this_fails()
except ZeroDivisionError as err:
    print('Handling run-time error:', err)

class MyErr(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self, value):
        return repr(self.value)

try:
    raise MyErr(2*2)
except MyErr as e:
    print("My exception occurred, value:", e.value)


class Error(Exception):
    """Base class for exceptions in this module."""
    pass


class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """

    def __init__(self, expression, message):
        self.expression = expression
        self.message = message


class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """

    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message

# 定义清理行为
def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:
        print("result is", result)
    finally:
        print("executing finally clause")

divide(10, 0)

# 关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")
